import 'package:flutter/material.dart';
import 'package:flutter_getx/app/base/load_image.dart';
import 'package:flutter_getx/ext/ext.dart';
import 'package:flutter_getx/res/dimens/dimens.dart';
import 'package:flutter_getx/res/gaps.dart';

class FloatingButtonBackTop extends StatefulWidget {
  const FloatingButtonBackTop(this.controller, {Key? key}) : super(key: key);

  final ScrollController controller;

  @override
  _FloatingButtonBackTopState createState() => _FloatingButtonBackTopState();
}

class _FloatingButtonBackTopState extends State<FloatingButtonBackTop> {
  bool _showFloat = false;

  @override
  void initState() {
    super.initState();

    widget.controller.addListener(() {
      var offset = widget.controller.offset;
      //print("offset = $offset");
      bool isShow = offset >= 240;
      if (_showFloat != isShow) {
        setState(() {
          _showFloat = isShow;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return _showFloat
        ? FloatingActionButton(
            backgroundColor: Colors.transparent,
            elevation: 0,
            mini: true,
            highlightElevation: 0,
            child: LoadImage(
              'float_up'.png,
              width: Dp.dp_45,
              height: Dp.dp_45,
            ),
            //tooltip: 'Back top',
            onPressed: () {
              widget.controller.animateTo(
                0,
                duration: const Duration(milliseconds: 100),
                curve: Curves.bounceIn,
              );
            },
          )
        : Gaps.empty;
  }
}

class CustomFloatingActionButtonLocation extends FloatingActionButtonLocation {
  final FloatingActionButtonLocation location;
  final double offsetX; // X方向的偏移量
  final double offsetY; // Y方向的偏移量
  const CustomFloatingActionButtonLocation(this.location, this.offsetX,
      this.offsetY);

  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    Offset offset = location.getOffset(scaffoldGeometry);
    return Offset(offset.dx + offsetX, offset.dy + offsetY);
  }
}

class NoScalingAnimation extends FloatingActionButtonAnimator {
  double _x = 0;
  double _y = 0;

  @override
  Offset getOffset(
      {required Offset begin, required Offset end, required double progress}) {
    _x = begin.dx + (end.dx - begin.dx) * progress;
    _y = begin.dy + (end.dy - begin.dy) * progress;
    return Offset(_x, _y);
  }

  @override
  Animation<double> getScaleAnimation({required Animation<double> parent}) {
    return Tween<double>(begin: 1.0, end: 1.0).animate(parent);
  }

  @override
  Animation<double> getRotationAnimation({required Animation<double> parent}) {
    return Tween<double>(begin: 1.0, end: 1.0).animate(parent);
  }
}

const CustomFloatingActionButtonLocation kBackTopLocation = CustomFloatingActionButtonLocation(
    FloatingActionButtonLocation.endFloat, 10, -80);
